'use strict';

/* Controllers */

app.controller('requirementCtrl', ['$scope', '$http', '$modal', '$log', '$location', '$stateParams', '$rootScope', 'lodash','$timeout', function ($scope, $http, $modal, $log, $location, $stateParams, $rootScope, lodash,$timeout) {
    $rootScope.initBreadcrumb($scope.breadcrumb);
    $scope.breadcrumb.push('产品设计');
    $scope.issuesList = [];   //获取业务线集合
    $scope.urlKeyword = "";   //url中的关键字
    $scope.urlAccount = "";   //url中的负责人
    $scope.urlStatus = "";   //url中的状态
    $scope.urlType = "";   //url中的业务线（暂时不用）
    $scope.urlLine = "";   //url中的产品线

    $scope.allProdcutLine = []; //产品线集合
    $scope.typeList = [];  //业务线集合
    $scope.accountList = [];  //负责人集合
    $scope.statusList = [];  //状态集合
    $scope.selected = [];
    //页面加载时，给headerElement设置元素
    $rootScope.initHeaderElements($scope.settings);
    $scope.settings.searchEle = {
        show: true,                   //显示查询框
        func: function (keyword) {     //点击查询框调用的方法
            $scope.urlKeyword = keyword ? keyword : "";
            searchReqList();
        },
        blurFunc: function (keyword) {
            $scope.urlKeyword = keyword ? keyword : "";
        }
    };
    $scope.settings.dateRadios = {
        show: true,
        radios: config_date_radios,
        init:2,
        func: function (startDate) {
             $scope.info.searchC.startDate=startDate;
             searchReqList();
        }
    }
    var addReqDesign = {
        show: true,
        label: "新建产品设计",
        func: function () {
            openDesignModal();
        }
    };
    var addProjectPlan = {
        show: true,
        label: "立项",
        func: function () {
            $scope.addProjectPlan('add');
        }
    };
    if($rootScope.isUserCanOperateByRole('pdm')){
        $scope.settings.btnEle.push(addReqDesign);
        $scope.settings.btnEle.push(addProjectPlan);
    }
    //结束header设置

    $scope.info = {
        tableScope: {},
        searchC: {},
        irTrueProjectPlanInfoLock: false,
        projectPlanInfo: {},
        check: true,      //显示列表复选框
        thdata: [
            {"thName": "标题"},
            {"thName": "产品线"},
            {"thName": "PDM负责人"},
            {"thName": "更新人"},
            {"thName": "更新时间"},
            {"thName": "项目计划"},
            {"thName": "状态"}
        ],
        page: {"isTrue": true},
        reqList: {
            "isOperation": {
                "Online": {"isTrue": true, "msg": "上线"}
            },
            "tdName": [
                {"name": "reqName"},
                {"name": "productLineName"},
                {"name": "reqChargerName"},
                {"name": "reqUpdateRealname"},
                {"name": "reqUpdateTime"},
                {"name": "projectPlanName"},
                {"name": "reqStatusName"}
            ]
        }
    };
    $scope.settings.switchs.push({
        label: "显示已上线产品设计",
        check: false,
        checkFun: function (check) {
            $scope.info.searchC.showOnline = check;
            searchReqList();
        }
    });

    setFondness();
    getIssuseType();

    //获取偏好设置
    function setFondness() {
        var fondness = getFondness("/api/v1/brdRequirement/getBrdRequirements");
        if (fondness) {
            $scope.urlLine = fondness.productLineId ? fondness.productLineId : "";
            $scope.urlStatus = fondness.status ? fondness.status : "";
            $scope.urlAccount = fondness.chargerAccount ? fondness.chargerAccount : "";
        }
    }

    //获取业务线集合
    function getIssuseType() {
        var url = sys_config_url + "/select/get?type=BRD_BUSINESS";
        $http.get(url).success(function (result) {
            if (result.code == "0") {
                if (result.data) {
                    angular.forEach(result.data.BRD_BUSINESS, function (issue) {
                        issue.name = issue.value;
                    });
                    $scope.typeList = result.data.BRD_BUSINESS;
                    setHeaderIssueType(result.data.BRD_BUSINESS);
                    getUserList(result.data.BRD_BUSINESS);
                } else {
                    $rootScope.toasterErrorInfo("获取业务线数据错误！");
                }
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    //设置header中的业务线
    function setHeaderIssueType(issuesList) {
        var issueSelectEle = {
            status: false,
            label: "全部业务线",
            eleList: issuesList,
            func: function (item) {
                issueSelectEle.crtName = item ? item.name : issueSelectEle.label;
                $scope.urlType = item ? item.key : null;
                searchReqList();
            }
        };
        // $scope.settings.selectEle.push(issueSelectEle);
    };

    //获取用户集合
    function getUserList(issueTypeList) {
        var url = beetle_auth_url + "/user/?token_id=" + getTokenId();
        $http.get(url).success(function (result) {
            if (result.success) {
                if (result.data) {
                    var accountArray = [{"crtname": "全部负责人", "id": 0}];
                    angular.forEach(result.data, function (data) {
                        data.crtname = data.realname;
                        accountArray.push(data);
                    });
                    $scope.accountList = result.data;
                    setHeaderUser(accountArray);
                    getStatusList(issueTypeList, result.data);
                } else {
                    $rootScope.toasterErrorInfo("获取用户数据错误！");
                }
            } else {
                $rootScope.toasterErrorInfo(result.msg);
            }
        });
    };

    //设置header中的用户（负责人）
    function setHeaderUser(userList) {
        var fondnessAccount = "";
        if ($scope.urlAccount) {
            var crtAccount = lodash.findWhere(userList, {"account": $scope.urlAccount});
            crtAccount.crtname = crtAccount.realname;
            fondnessAccount = crtAccount;
        } else {
            fondnessAccount = {"crtname": "全部负责人", "id": 0};
        }
        var userSelectEle = {
            status: true,
            items: userList,
            prompt: "请选择负责人",
            selectedItem: fondnessAccount,
            func: function (item) {
                $scope.urlAccount = item.account ? item.account : "";
                searchReqList();
            }
        };
        $scope.settings.uiSltEle.push(userSelectEle);
    };

    //获取产品设计状态集合
    function getStatusList(issueTypeList, userList) {
        var url = sys_config_url + "/select/get?type=BRD_STATUS";
        $http.get(url).success(function (result) {
            if (result.code == "0") {
                angular.forEach(result.data.BRD_STATUS, function (status) {
                    status.name = status.value;
                });
                $scope.statusList = result.data.BRD_STATUS;
                setHeaderStatus(result.data.BRD_STATUS);
                getProductLine(issueTypeList, userList, result.data.BRD_STATUS);
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    //设置header中的产品设计状态
    function setHeaderStatus(statusList) {
        var fondnessIssueType = "";
        if ($scope.urlStatus) {
            var crtIssueType = lodash.findWhere(statusList, {"key": $scope.urlStatus});
            fondnessIssueType = crtIssueType.value;
        } else {
            fondnessIssueType = "全部状态";
        }
        var statusSelectEle = {
            status: true,
            crtName: fondnessIssueType,
            label: "全部状态",
            eleList: statusList,
            func: function (item) {
                statusSelectEle.crtName = item ? item.name : statusSelectEle.label;
                $scope.urlStatus = item ? item.key : "";
                searchReqList();
            },
        };
        $scope.settings.selectEle.push(statusSelectEle);
    };


    //获取产品线集合
    function getProductLine(issueTypeList, userList, statusList) {
        var url = matrix_product_url + "/productLine/getProductLineTree";
        $http.get(url).success(function (result) {
            if (result.code == "0") {
                var array = [];
                var oneLevelArray = flattenDeep(result.data.children, array);
                $scope.allProdcutLine = oneLevelArray;
                setHeaderLine(result.data.children, oneLevelArray);
                searchReqList(issueTypeList, userList, statusList, oneLevelArray);
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    //将多级数据改成一级
    function flattenDeep(data, array) {
        angular.forEach(data, function (d) {
            array.push(d);
            if (d.children && d.children.length) {
                flattenDeep(d.children, array);
            }
        });
        return array;
    };

    //设置header中的产品线
    function setHeaderLine(prodcutLineList, oneLevelArray) {
        var defaultLineName = "";
        if ($scope.urlLine) {
            var crtLineItem = lodash.findWhere(oneLevelArray, {"id": $scope.urlLine});
            defaultLineName = crtLineItem.name;
        } else {
            defaultLineName = "全部产品线";
        }
        $scope.settings.sltTree = {
            show: true,
            name: defaultLineName,
            label: "全部产品线",
            data: prodcutLineList,
            func: function (item) {
                $scope.settings.sltTree.name = item ? item.name : "全部产品线";
                $scope.urlLine = item ? item.id : "";
                searchReqList();
            },
            cancelFunc: function (item) {
                $scope.urlLine = "";
                $scope.settings.sltTree.name = null;
                searchReqList();
            }
        };
    };

    //查询产品设计(req)集合
    function searchReqList(issueTypeList, userList, statusList, prodcutLineList) {
        var url = matrix_product_url + "/brdRequirement/getBrdRequirements";
        var urlArray = [
            {"type": "reserveHabit", "param": 1},
            {"type": "tokenId", "param": getTokenId()},
            {"type": "productLineId", "param": $scope.urlLine},
            {"type": "status", "param": $scope.urlStatus},
            {"type": "chargerAccount", "param": $scope.urlAccount},
            {"type": "withFeatureDesc", "param": "0"},
            {"type": "keyword", "param": $scope.urlKeyword}];

        if ($scope.info.searchC.showOnline) {
            urlArray.push({"type": "isOnline", "param": $scope.info.searchC.showOnline})
        }
        if ($scope.info.searchC.startDate) {
            urlArray.push({"type": "startDate", "param": $scope.info.searchC.startDate})
        }

        url = $rootScope.setUrlParams(url, urlArray);

        $timeout(function () {
            $http.get(url).success(function (result) {
                if (result.code == "0") {
                    $scope.info.reqList.datas = result.data;
                    var userArray = userList ? userList : $scope.accountList;
                    var statusArray = statusList ? statusList : $scope.statusList;
                    var prodcutLineArray = prodcutLineList ? prodcutLineList : $scope.allProdcutLine;
                    angular.forEach($scope.info.reqList.datas, function (req) {
                        //设置负责人
                        var chargerItem = lodash.findWhere(userArray, {"account": req.reqChargerAccount});
                        req.reqChargerName = chargerItem ? chargerItem.realname : req.reqChargerAccount;
                        //设置状态
                        var statusItem = lodash.findWhere(statusArray, {"key": req.reqStatus});
                        req.reqStatusName = statusItem ? statusItem.value : req.reqStatus;
                        //设置产品线
                        var productLineItem = lodash.findWhere(prodcutLineArray, {"id": req.productLineId});
                        req.productLineName = productLineItem ? productLineItem.name : req.productLineId;
                        req.reqUpdateTime = req.reqUpdateTime ? timestampToTime(req.reqUpdateTime) : timestampToTime(req.reqCreateTime);
                    });
                    $scope.info.page.isTrue = result.data.length > 30 ? true : false;
                } else {
                    $rootScope.toasterErrorInfo(result.desc);
                }
            });
        })

    };

    function openDesignModal() {
        var modalInstance = $modal.open({
            animation: true,
            templateUrl: getTemplateUrl("matrix/component/tpl/designModel.html"),
            controller: "designCtrl",
            keyboard: true,
            backdrop: true,
        });

        //点击modal新增后，把feature值传过来
        modalInstance.result.then(function (data) {
            if (data.trData.length) {
                createDesign(data);
            } else {
                createReqIssue(data, "");
            }
        }, function (reason) {
            cancelModal(reason);
        });
    };

    //保存表格数据，然后获取id
    function createDesign(data) {
        angular.forEach(data.trData, function (tr) {
            if (tr.sltToAccount) {
                delete tr.sltToAccount
            }
            if (tr.sltUser) {
                delete tr.sltUser
            }
        })
        var postParams = {"issues": data.trData};
        var url = matrix_product_url + "/issue/saveIssues";
        $http({
            method: "post",
            url: url,
            data: JSON.stringify(postParams),
            headers: {"Content-Type": "application/json"}
        }).success(function (result) {
            if (result.code == "0") {
                if (result.data) {
                    var issuesList = "";
                    angular.forEach(result.data, function (issue) {
                        issuesList += issue.id + ",";
                    });
                    createReqIssue(data, issuesList);
                } else {
                    $rootScope.toasterErrorInfo("批量创建Issue时，返回数据错误！");
                }
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    //创建req
    function createReqIssue(data, issuesList) {
        var postParams = {
            reqName: data.design.title,
            reqDesc: data.design.desc,
            reqCreaterAccount: getUserAccount(),
            reqCreaterRealname: getUserName(),
            productLineId: data.design.productLineId,
        };
        if (data.isCreatePP) {
            postParams.newPlan = 1;
            postParams.projectFlag = "DC";
            postParams.tokenId = getTokenId();
        }
        if (issuesList) {
            postParams.issues = lodash.trimRight(issuesList, ',');
        }
        var url = matrix_product_url + "/brdRequirement/saveBrdRequirement";
        $http({
            method: "post",
            url: url,
            data: JSON.stringify(postParams),
            headers: {"Content-Type": "application/json"}
        }).success(function (result) {
            if (result.code == "0") {
                if (result.data) {
                    if (data.isChecked) {
                        window.location.href = "#/app/req/summary/" + result.data;
                    } else {
                        $rootScope.toasterSuccessInfo("添加成功！");
                        searchReqList();
                    }
                } else {
                    $rootScope.toasterErrorInfo("归纳产品设计时返回数据错误！");
                }
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    function cancelModal() {
        console.log("取消");
    };


    //根据type查看或修改req
    $scope.addOrEditReq = function (type, info) {
        // if(type != "view") {
        //     window.location.href = "#/app/matrix/requirementEdit/" + type + '/' + projectPlanInfo.reqId + "//";
        // } else {
        window.location.href = "#/app/req/summary/" + info.reqId;
        // }
    }

    //控制创建按钮
    $scope.lock = function () {
        var lock = true;
        angular.forEach($scope.info.reqList.datas, function (data) {
            if (data.check) {
                lock = false;
                return;
            }
        })
        return lock;
    }

    //功能 用所选需求createPRD
    $scope.addProjectPlan = function (type) {
        var filterSltArray = [];
        angular.forEach($scope.selected, function (sltItem) {
            var hasItem = lodash.findIndex(filterSltArray, function (filterItem) {
                return filterItem.reqId == sltItem.reqId;
            });

            if (hasItem == -1) {
                filterSltArray.push(sltItem);
            }
        });
        var reqs = [];
        angular.forEach(filterSltArray, function (data) {
            if (data.reqStatus == 'NEW' || data.reqStatus == 'DISSOCIATION') {
                reqs.push(data)
            }
        })
        // if (reqs.length == 0) {
        //     $rootScope.toasterWarningInfo("至少选择一个'新提交'或者'移出项目计划'状态的需求!");
        //     return false;
        // }

        $rootScope.projectPlanSaveShow(reqs, $scope.statusList, null, function (reqIds) {
            if (reqIds != false) {
                if (reqIds.length > 0) {
                    angular.forEach(reqIds, function (reqId) {
                        var crtReqItem = lodash.findWhere($scope.selected, {"reqId": reqId});
                        crtReqItem.reqStatus = "P_PLAN";
                        crtReqItem.reqStatusName = "生成项目计划";
                        crtReqItem.reqStatusShow = "生成项目计划";
                    });
                }
            }
        })
    };

    //req 上线
    $scope.reqOnline = function (info) {
        if (info.reqStatus != "P_PLAN") {
            $rootScope.toasterWarningInfo("只有【生成项目计划】状态数据才能上线！");
            return false;
        }
        if (info.reqStatus == "COMPLETED") {
            $rootScope.toasterWarningInfo("已上线的需求不能重复上线！");
            return false;
        }
        var confirmParams = {
            "titleData": "提示",
            "bodyData": "确定要上线【" + info.reqName + "】吗？"
        };
        $rootScope.confirmWindow(confirmParams, function () {
            var url = matrix_product_url + "/brdRequirement/operateForReqOnline?reqIds=" + info.reqId;
            $http.get(url).success(function (res) {
                if (res.code == "0") {
                    info.reqStatus = "COMPLETED";
                    info.reqStatusName = "已上线";
                    $rootScope.toasterSuccessInfo("需求【" + info.reqName + "】上线成功!");
                } else {
                    $rootScope.toasterErrorInfo(res.desc);
                }
            })
        })
    }

}]);

app.controller("designCtrl", ["$scope", "$rootScope", "$modalInstance", "$http", "$filter", "lodash", function ($scope, $rootScope, $modalInstance, $http, $filter, lodash) {
    $scope.type = "new";
    $scope.designTitle = "新建产品设计";

    $scope.showAlertMessage = function () {
        $(".alert-danger").css("display", "block");
    };

    $scope.hideAlertMessage = function () {
        $(".alert-danger").css("display", "none");
    };


    $scope.createClick = function (data) {
        if (!data.design.title) {
            $(".form-input-title").focus();
            $rootScope.toasterWarningInfo("请输入标题");
            return false;
        }
        if (!data.design.desc) {
            $(".form-input-desc").focus();
            $rootScope.toasterWarningInfo("请输入描述");
            return false;
        }
        $modalInstance.close(data);
    };

    $scope.cancelClick = function () {
        $modalInstance.dismiss("cancel");
    };
}]);